/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: This class handles web service calls associated with standard catalog searches.
 * 
 */
package us.in.lib.acpl.Mobile_ACPL.ws;

import us.in.lib.acpl.Mobile_ACPL.R;
import us.in.lib.acpl.Mobile_ACPL.SearchActivity;
import us.in.lib.acpl.Mobile_ACPL.SearchResultsActivity;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import us.in.lib.acpl.Mobile_ACPL.adapters.SearchResultListAdapter;
import us.in.lib.acpl.Mobile_ACPL.item.SearchResultTitle;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

public class MainSearchHandler extends SearchCatalogHandler {

	private SearchActivity act;
	private SearchResultsActivity resultsAct;
	private Handler handler;
	private List<SearchResultTitle> list;
	public MainSearchHandler(SearchActivity act) {
		super();
		this.act = act;
		handler = new Handler();
	}

	@Override
	public void search(String term, int resultsPerPage,
			String searchTypeFilter, String searchLibraryFilter,
			String materialTypeFilter) {
		this.term = term;
		this.materialTypeFilter = materialTypeFilter;
		new SearchCatalogTask().execute(term, searchTypeFilter,
				searchLibraryFilter, materialTypeFilter);

	}

	@Override
	public void getMoreResults(SearchResultsActivity act) {
		resultsAct = act;
		new GetMoreResultsTask().start();
	}

	@Override
	public String getTerm() {
		return term;
	}

	@Override
	public void setTerm(String term) {
		this.term = term;
	}

	@Override
	public void setQueryID(String id) {
		this.queryID = id;
	}

	@Override
	public void displaySearchResults(List<SearchResultTitle> list) {

		results = list;
		act.handleSearchResults(list);
	}

	@Override
	public String getQueryID() {
		return queryID;
	}

	@Override
	public List<SearchResultTitle> getResults() {
		return results;
	}

	@Override
	public void setResults(List<SearchResultTitle> results) {
		this.results = results;
	}

	@Override
	public long getTotalResults() {
		return totalResults;
	}

	@Override
	public void setTotalResults(long totalResults) {
		this.totalResults = totalResults;
	}

	@Override
	public boolean hasMoreResults() {
		if (pageToGet * RESULTS_PER_PAGE + 1 > totalResults) {
			return false;
		} else {
			return true;
		}
	}

	private class SearchCatalogTask extends
			AsyncTask<Object, Void, List<SearchResultTitle>> {


		@Override
		protected List<SearchResultTitle> doInBackground(Object... params) {

			String searchTerm = (String) params[0];
			String searchTypeFilter = (String) params[1];
			String searchLibraryFilter = (String) params[2];

			String response = doSearchCatalogRequest(searchTerm,
					searchTypeFilter, searchLibraryFilter);
			List<SearchResultTitle> list = null;
			try {
				list = parseResponse(response);
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<SearchResultTitle> result) {

			if (result == null) {
				Toast toast = Toast.makeText(act, "Connection error",
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				act.findViewById(R.id.searchBar).setVisibility(View.GONE);
				act.findViewById(R.id.searchButton).setVisibility(View.VISIBLE);
			} else {
				setResults(result);

				act.handleSearchResults(result);
			}

		}

	}

	private class GetMoreResultsTask extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			list = new ArrayList<SearchResultTitle>();

			String response = doGetMoreResults();

			try {
				list = parseResponse(response);
			} catch (XmlPullParserException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}

			
	          handler.post(new Runnable() {
	              @Override
	              public void run() {
	      			if (list == null) {
	    				Toast toast = Toast.makeText(act, "Connection error",
	    						Toast.LENGTH_LONG);
	    				toast.setGravity(Gravity.CENTER, 0, 0);
	    				toast.show();
	    			} else {
	    				results.addAll(list);
	    				SearchResultListAdapter ad = (SearchResultListAdapter) resultsAct
	    						.getListAdapter();
	    				ad.notifyDataSetChanged();
	    				resultsAct.showMoreResults();
	    			}
	              }
	            });
		}

	}
}
